extends KinematicBody2D

class_name Projectile

const PROJECTILE_SPEED = 400

export var direction = Vector2(0, 1)
export var projectile_material = -3
export var disabled = false

func _fixed_process(delta):
	var motion = direction * PROJECTILE_SPEED * delta
	var collision_info = move_and_collide(motion)

	if (has_node("particles")):
		var theta = rad2deg(Vector2(0, -1).angle_to(direction))
		get_node("particles").set_param(0, theta)

	if (collision_info):
		var collider = collision_info.collider
		if (collider is TileMap):
			var coords = position / 32 + direction / 4.0
			coords.x = int(coords.x)
			coords.y = int(coords.y)
			var collided_tile = collider.get_cell(coords.x, coords.y)
			if (collided_tile > -1):
				print("Collision with tile at " + str(coords))
				if (collided_tile == projectile_material):
					disable(true)
					collider.set_cell(coords.x, coords.y, -1)
				else:
					disable(false)
		elif (collider is MovingCreature and !collider.is_player()):
			print("Collision with moving enemy")
			if (collider.armor_type == projectile_material):
				disable(true)
				collider.dead = true
			else:
				disable(false)


	if (disabled):
		queue_free()

func disable(destroyed=false):
	if (destroyed):
		get_parent().get_node("player").get_node("mapsounds").play("destroy")
	else:
		get_parent().get_node("player").get_node("mapsounds").play("nodestroy")
	disabled = true
